package com.coincalf.chan.controller;

import com.coincalf.chan.websocket.ChannelWebsocketStarter;
import com.coincalf.chan.websocket.vo.ResponseEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tio.core.Aio;
import org.tio.server.ServerGroupContext;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

/**
 * @author qiang
 */
@Slf4j
@RestController
@RequestMapping("/v3/messaging")
public class MessagingController {

    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping("/convertAndSendToGroup")
    public void convertAndSendToGroup(String channel, String body) {
        //channel -> market.btcusdt.kline.1hour
        //body -> {"tick":[[1609149600000,19186.24,19186.24,19186.24,19186.24,0.0]]}
        ServerGroupContext serverGroupContext = ChannelWebsocketStarter.getServerGroupContext();
        if (Optional.ofNullable(serverGroupContext).isPresent()) {
            ResponseEntity responseEntity = new ResponseEntity()
                    .setId(serverGroupContext.getId())
                    .setCh(channel);
            try {
                Map<String, Object> map = objectMapper.readValue(body, Map.class);
                responseEntity.putAll(map);
            } catch (IOException e) {
                responseEntity.put("result", body);
            }
            //channel=market.btcusdt.depth.step1
            //responseEntity=org.tio.websocket.common.WsResponse@2552f3f
            //serverGroupContext=org.tio.server.ServerGroupContext@165d9151
            //channel=market.btcusdt.depth.step2
            Aio.sendToGroup(serverGroupContext, channel, responseEntity.build());
        }
    }

    @PostMapping("/convertAndSendToUser")
    public boolean convertAndSendToUser(String channel, String userId, String body) {
        ServerGroupContext serverGroupContext = ChannelWebsocketStarter.getServerGroupContext();
        if (Optional.ofNullable(serverGroupContext).isPresent()) {
            ResponseEntity responseEntity = new ResponseEntity()
                    .setId(serverGroupContext.getId())
                    .setEvent(channel);
            try {
                Map<String, Object> map = objectMapper.readValue(body, Map.class);
                responseEntity.putAll(map);
            } catch (IOException e) {
                responseEntity.put("result", body);
            }
            return Aio.sendToUser(serverGroupContext, userId, responseEntity.build());
        }
        return false;
    }

}
